import React, { useState, useEffect, useRef } from 'react';
import Particles, { initParticlesEngine } from "@tsparticles/react";
import { loadSlim } from "@tsparticles/slim";
import './GiftAnimation.css';

const GiftAnimation = ({ giftQueue, onAnimationComplete }) => {
  const [init, setInit] = useState(false);
  const [activeGift, setActiveGift] = useState(null);
  const [animationKey, setAnimationKey] = useState(0);
  const timeoutRef = useRef(null);
  const processingRef = useRef(false);
  const isFirstRender = useRef(true);

  // 初始化粒子引擎
  useEffect(() => {
    initParticlesEngine(async (engine) => {
      await loadSlim(engine);
    }).then(() => {
      setInit(true);
    });

    // 组件卸载时清理
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
        timeoutRef.current = null;
      }
    };
  }, []);

  // 处理礼物队列
  useEffect(() => {
    // 跳过首次渲染
    if (isFirstRender.current) {
      isFirstRender.current = false;
      return;
    }

    // 如果已经有活跃的礼物或者正在处理中，不执行任何操作
    if (activeGift || processingRef.current || giftQueue.length === 0) {
      return;
    }

    // 标记为正在处理，防止重复触发
    processingRef.current = true;

    // 显示队列中的第一个礼物
    console.log(`准备显示礼物: ${giftQueue[0].gift.name}, 队列长度: ${giftQueue.length}`);
    setActiveGift(giftQueue[0]);
    setAnimationKey(prev => prev + 1);

    // 设置动画结束的定时器
    timeoutRef.current = setTimeout(() => {
      console.log(`礼物动画结束: ${activeGift?.gift?.name || '未知礼物'}`);
      
      // 清除当前礼物
      setActiveGift(null);
      
      // 重置处理标志
      processingRef.current = false;
      
      // 通知父组件移除队列中的第一个礼物
      if (giftQueue.length > 0) {
        onAnimationComplete();
      }
    }, 4000);
  }, [giftQueue, activeGift, onAnimationComplete]);

  // 如果没有初始化完成或没有活跃礼物，不渲染任何内容
  if (!init || !activeGift) {
    return null;
  }

  // 根据礼物类型选择粒子效果配置
  const getParticlesOptions = () => {
    if (activeGift.gift.id !== 'rocket') return null;

    return {
      fullScreen: { enable: false },
      particles: {
        number: {
          value: 80,
          density: { enable: true, value_area: 800 }
        },
        color: { value: ["#fdcf58", "#757676", "#f27d0c", "#800909", "#f07f13"] },
        shape: { type: "circle" },
        opacity: {
          value: { min: 0.1, max: 0.5 },
          animation: { enable: true, speed: 1, sync: false }
        },
        size: {
          value: { min: 1, max: 5 },
          animation: { enable: true, speed: 5, sync: false }
        },
        move: {
          enable: true,
          speed: 6,
          direction: "top",
          straight: true,
          outModes: { default: "destroy" }
        }
      },
      interactivity: {
        detectsOn: "canvas",
        events: { resize: true }
      },
      detectRetina: true,
      background: { color: "transparent" },
      emitters: {
        direction: "top",
        position: { x: 50, y: 120 },
        rate: { quantity: 5, delay: 0.15 },
        size: { width: 10, height: 10 }
      }
    };
  };

  const { fromUser, gift } = activeGift;
  const particlesOptions = getParticlesOptions();

  return (
    <div className="gift-animation-container" key={`gift-container-${animationKey}`}>
      {gift.id === 'rocket' && particlesOptions && (
        <Particles id={`tsparticles-${animationKey}`} options={particlesOptions} />
      )}
      <div className="gift-banner">
        <span className="gift-user">{fromUser.nickname || '匿名用户'}</span>
        <span>&nbsp;送出了&nbsp;</span>
        <span className="gift-name">{gift.name}</span>
      </div>
      <img 
        src={gift.icon} 
        alt={gift.name} 
        className={`gift-image ${gift.id}`} 
        onError={(e) => {
          console.log("礼物图片加载失败，使用备用图片");
          e.target.onerror = null;
          e.target.src = '/assets/gifts/default.svg';
        }}
        style={{
          maxWidth: '150px',
          maxHeight: '150px',
          objectFit: 'contain'
        }}
      />
    </div>
  );
};

export default GiftAnimation; 